#-*- coding: utf-8 -*-
import sys
import socket,time

class Udpserver(object):
    def __init__(self, _port):
        self.host = ''
        self.port = _port
        self.server = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)


    # UPD下发送消息,检查设备是否在线
    def initConnect(self, _initCmd):
        self.brodaCastMessage(_initCmd)

    # UDP发送消息
    def sendMessage(self, _distIp, _cmd):
        self.host = _distIp
        ADDR = (self.host, self.port)
        self.server.sendto(_cmd.encode('utf-8'), ADDR)
        return True

    # UPD接受消息
    def recMessage(self, _timeout):
        self.server.settimeout(_timeout)
        ADDR = ('', self.port)
        self.server.bind(ADDR)
        recvData = self.server.recvfrom(1024)
        content, destInfo = recvData
        print content, destInfo
        return destInfo,content.decode("utf-8") 

    def brodaCastMessage(self, _cmd):
        self.server.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        host_ip = self.get_host_ip()
        host_broad_ip = host_ip[:host_ip.rfind('.')]+'.255'
        ADDR = (host_broad_ip, self.port)
        self.server.sendto(_cmd, ADDR) 

    def get_host_ip(self):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(('8.8.8.8', 80))
            ip = s.getsockname()[0]
        finally:
            s.close()
        return ip

     
    def serverClose(self):
        self.server.close()
        
if __name__ == '__main__':
    udpserver = Udpserver(10012)
    print socket.gethostbyname(socket.gethostname())
    udpserver.brodaCastMessage('ffff')
    #udpserver.recMessage(10)
    udpserver.serverClose()